package com.mqtt.demo.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @ClassName MyMqttClient
 * @Description mqtt连接管理类
 * @Author zhengmw
 * @Data 2024/7/25 18:09
 */
@Slf4j
@Component
public class MqttManager {

    @Value("${mqtt.broker}")
    private String broker;

    @Value("${mqtt.clientId}")
    private String clientId;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    /**
     * @Description 建立连接
     *
     * @Return org.eclipse.paho.client.mqttv3.MqttClient
     * @Author zhengmw
     * @Date 2024/7/25 18:17
     */
    public MqttClient connect() throws MqttException {
        MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setUserName(username);
        connectOptions.setPassword(password.toCharArray());
        // 保留会话
        connectOptions.setCleanSession(true);
        client.connect();
        log.info("*******mqtt连接建立成功, broker:{}", broker);
        return client;
    }
}
